import numpy as np
import cv2

img = cv2.imread("images.png", 0)

# 对图像进行SVD分解
U, S, V = np.linalg.svd(img.astype(np.float64), full_matrices=False)

# 定义保留的奇异值数量
k = 30
S_k = np.diag(S[:k])

# 重构图像
img_reconstructed = np.dot(U[:, :k], np.dot(S_k, V[:k, :]))
img_reconstructed = np.clip(img_reconstructed, 0, 255).astype(np.uint8)

# 横向对比拼接
combined_image = cv2.hconcat([img, img_reconstructed])

# 显示图像
cv2.imshow("Original - Increased Contrast - Decreased Contrast", combined_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 保存重构后的图像
cv2.imwrite("reconstructed_image.jpg", img_reconstructed)
